package com.link.base.base.contacts.controller;

import com.link.base.base.accnt.model.Account;
import com.link.base.base.accnt.service.AccountService;
import com.link.base.base.contacts.model.Contacts;
import com.link.base.base.contacts.service.ContactsService;
import com.link.base.base.user.model.User;
import com.link.core.cllog.LCLogger;
import com.link.core.basic.annotations.JsonParam;
import com.link.core.basic.controller.BasicController;
import com.link.core.basic.model.BasicModel;
import com.link.core.basic.query.Filter;
import com.link.core.basic.query.QueryParams;
import com.link.core.basic.service.BasicService;
import com.link.core.basic.service.ServiceException;
import com.link.core.util.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
 * 联系人controller
 *
 * @author  unknwon
 * @date:   2018/11/9 14:04
 * @version 1.0
 */

@Controller
@RequestMapping("/link/contacts")
public class ContactsController extends BasicController<Contacts> {

    @Resource
    private ContactsService contactsService;

    @Resource
    private AccountService accountService;

    @Override
    public BasicService<Contacts> getBasicService() throws Exception {
        return contactsService;
    }

    /**
     *  通过客户id查询联系人
     */
    @RequestMapping(value = "/listByAcctId", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> listByAcctId(@JsonParam QueryParams qps, HttpSession session,
                                            HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        List<Contacts> list = null;
        Contacts entity = new Contacts();
        try {
            qps.invokePreFilterAndSorter();
            qps.preDealSecurity(request);
            Contacts t = (Contacts) BasicModel.transformClass(entity.getClass(), qps);
            beforQueryAllOrExample(t, request);
            beforQueryExample(t, request);
            if (qps.getAttr1() != null && !"".equals(qps.getAttr1())) {
                t.setAcctId(Long.parseLong(qps.getAttr1()));

            } else {
                throw new ServiceException("PUBLIC-026");
            }
            list = contactsService.queryByExamplePage(t);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(t, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Contacts>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 更新前设置有效字段为Y
     */
    @Override
    public void beforUpdate(Contacts entity, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(entity.getIsEffective())) {
            entity.setIsEffective("Y");
        }
    }

    /**
     * 更新前设置有效字段为Y
     */
    @Override
    public void beforInsert(Contacts entity, HttpServletRequest request) throws Exception {
        if (StringUtils.isBlank(entity.getIsEffective())) {
            entity.setIsEffective("Y");
        }
    }

    /**
     * 导入前通过客户名称查询客户id写入到联系人信息中
     *
     * @author unknown
     * @param record
     * @param request
     */
    @Override
    public void beforeImport(Contacts record, HttpServletRequest request) {
        QueryParams qps = new QueryParams();
        qps.setPageFlag(false);
        qps.addFilter(new Filter("acctName", record.getAcctName()));
        Account entity = (Account) BasicModel.transformClass(Account.class, qps);
        try {
            List<Account> list = accountService.queryByExamplePage(entity);
            //这里会不会有空指针异常的风险？
            record.setAcctId(list.get(0).getId());
        } catch (Exception e) {
            LCLogger.withException(e);
        }
    }

    /**
     * 选择父对象时的picklist
     */
    @RequestMapping(value = "/parentPicklist", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> parentPicklist(@JsonParam Contacts entity,@JsonParam QueryParams qps, HttpSession session,
                                              HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Contacts contacts = (Contacts) BasicModel.transformClass(Contacts.class, qps);
            //设置安全性
            contacts.preDealSecurity(request);
            List<Contacts> list = contactsService.queryContactsListRemoveIdAndChildrenPage(contacts);
            result.put("success", true);
            result.put("rows", list);
            result.put("total", getCount(contacts, list.size()));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("rows", new ArrayList<Contacts>());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 加载树
     */
    @RequestMapping(value = "/treelist")
    @ResponseBody
    public Map<String, Object> treelist(@JsonParam Contacts entity, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            List<Contacts> list = contactsService.contactsTreeList(entity);
            result.put("success", true);
            result.put("tree", true);
            //传根节点
            result.put("list", list.get(0));
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("list", new Contacts());
            result.put("result", e.getMessage());
        }
        return result;
    }

    /**
     * 客户联系人创建用户账号
     */
    @RequestMapping(value = "/createdUserAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> createdUserAccount(@JsonParam Contacts entity,@JsonParam QueryParams qps,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            User user = contactsService.createdUserAccount(entity);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }


    /**
     * 客户联系人用户账号禁用
     */
    @RequestMapping(value = "/disableUserAccount", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> disableUserAccount(@JsonParam Contacts entity,@JsonParam QueryParams qps,
                                                  HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> result = new HashMap<String, Object>(4);
        try {
            Contacts object = contactsService.queryById(entity);
            if (null == object.getUserId()) {
                throw new ServiceException("CONTACTS-001");
            }
            contactsService.disableUserAccount(object);
            result.put("success", true);
        } catch (Exception e) {
            LCLogger.withException(e);
            result.put("success", false);
            result.put("result", e.getMessage());
        }
        return result;
    }
}
